﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UDS.Web.UI.Controls
{
    /// <summary>
    /// Displays a calendar icon.
    /// </summary>
    public class CalendarButton : WebControl
    {
        /// <summary>
        /// Specify the id of the target control
        /// </summary>
        [PersistenceMode(PersistenceMode.Attribute)]
        public string TargetControlID
        {
            get;
            set;
        }

        protected override void Render(HtmlTextWriter writer)
        {
            var id = TargetControlID;
            if (string.IsNullOrEmpty(id))
            {
                throw new InvalidOperationException("TargetControlID is required.");
            }
            var control = FindControl(id);
            if (control == null || !(control is TextBox))
            {
                throw new InvalidOperationException("TextBox control is required.");
            }

            writer.WriteBeginTag("a");
            writer.WriteAttribute("href", "javascript:void(0);");
            writer.WriteAttribute("onclick", string.Format("this.blur();document.getElementById('{0}').focus();", control.ClientID));
            writer.Write(" />");

            writer.WriteBeginTag("img");
            writer.WriteAttribute("id", ClientID);
            writer.WriteAttribute("src", ResolveClientUrl("~/Images/Calendar.png"));
            writer.WriteAttribute("border", "0");
            writer.WriteAttribute("align", "absMiddle");
            writer.Write(" />");

            writer.Write("</a>");
        }
    }
}